package com.blueocean_health.care.management.service.impl;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.domain.base.OrderChargeInfo;
import com.blueocean_health.care.management.domain.base.OrderInfo;
import com.blueocean_health.care.management.domain.base.OrderServiceInfo;
import com.blueocean_health.care.management.domain.base.User;
import com.blueocean_health.care.management.domain.base.UserAccount;
import com.blueocean_health.care.management.domain.dto.AppointmentOrderSelectInfoEntity;
import com.blueocean_health.care.management.domain.dto.ChargeInfoDto;
import com.blueocean_health.care.management.domain.dto.OrderDetailDto;
import com.blueocean_health.care.management.domain.dto.OrderInfoDto;
import com.blueocean_health.care.management.domain.dto.OrderSelectInfoEntity;
import com.blueocean_health.care.management.domain.dto.RelationListDto;
import com.blueocean_health.care.management.domain.dto.SOrderInfoEntity;
import com.blueocean_health.care.management.domain.dto.SOrderServiceInfoEntity;
import com.blueocean_health.care.management.domain.dto.SOrderServiceNurseInfoEntity;
import com.blueocean_health.care.management.domain.dto.SettlementDto;
import com.blueocean_health.care.management.domain.dto.SickRoomInfoDto;
import com.blueocean_health.care.management.domain.dto.WorkerDto;
import com.blueocean_health.care.management.domain.dto.WorkerInfoDto;
import com.blueocean_health.care.management.domain.ordervo.SelectOrderVo;
import com.blueocean_health.care.management.em.OrderTypeEnum;
import com.blueocean_health.care.management.em.OrderUpdateFlagEnum;
import com.blueocean_health.care.management.em.PayStatusEnum;
import com.blueocean_health.care.management.mapper.OrderChargeInfoMapper;
import com.blueocean_health.care.management.mapper.OrderInfoMapper;
import com.blueocean_health.care.management.mapper.OrderSelectInfoEntityMapper;
import com.blueocean_health.care.management.mapper.OrderServiceInfoMapper;
import com.blueocean_health.care.management.mapper.SOrderInfoEntityMapper;
import com.blueocean_health.care.management.mapper.UserAccountMapper;
import com.blueocean_health.care.management.mapper.UserMapper;
import com.blueocean_health.care.management.service.IChareOrderService;
import com.blueocean_health.care.management.service.IOrderSelectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Service
public class OrderSelectServiceImpl implements IOrderSelectService{
	@Resource
	private OrderSelectInfoEntityMapper orderSelectInfoEntityMapper;
	@Resource
	private OrderChargeInfoMapper orderChargeInfoMapper;
	@Resource
	private SOrderInfoEntityMapper sOrderInfoEntityMapper;
	@Resource
	private OrderInfoMapper orderInfoMapper;
	@Resource
	private IChareOrderService iChareOrderService;
	@Resource
	private UserAccountMapper userAccountMapper;
	@Resource
	private OrderServiceInfoMapper orderServiceInfoMapper;
	@Override
	//查询订单列表
	public Map<String, Object>  selectOrderList(SelectOrderVo order) {
		String sort = order.getSort()==null?"":order.getSort();
		if(sort.contains("remainingTime")){
			 sort = sort.replaceAll("remainingTime", "diff_date");
		}
		if(sort.contains("createTime")){
			 sort = sort.replaceAll("createTime", "create_time");
		}
		else{
			sort ="create_time  desc";
			}
		order.setSort(sort);
		if(!StringUtils.isEmpty(order.getStatus())){
			String[] split = order.getStatus().split("\\.");
			order.setOrderStatus(split[0]);
			if(split.length>1){
			order.setPayStatus(split[1]);
			}
		}
		if(!StringUtils.isEmpty(order.getBeginTime())){
			order.setBeginTime(order.getBeginTime()+" 00:00:00");
		}
		if(!StringUtils.isEmpty(order.getEndTime())){
			order.setEndTime(order.getEndTime()+" 23:59:59");
		}
		if(!StringUtils.isEmpty(order.getStartBillingTime())){
			order.setStartBillingTime(order.getStartBillingTime()+" 00:00:00");
		}
		if(!StringUtils.isEmpty(order.getEndBillingTime())){
			order.setEndBillingTime(order.getEndBillingTime()+" 23:59:59");
		}
		order.setIspage(false);
		//手动分页
		if(StringUtils.isEmpty(order.getUserId())&&StringUtils.isEmpty(order.getMaxReceiptNumber())
				&&StringUtils.isEmpty(order.getWorkerNames())&&StringUtils.isEmpty(order.getMinReceiptNumber())
				&&StringUtils.isEmpty(order.getTimeType())&&StringUtils.isEmpty(order.getStartBillingTime())
				&&StringUtils.isEmpty(order.getEndBillingTime())&&StringUtils.isEmpty(order.getServiceType())){
			order.setIspage(true); 
			int pagesizes=Integer.valueOf(StringUtils.isEmpty(order.getPageSize())?"65536":order.getPageSize()); 
			int fromIndex = (Integer.valueOf(StringUtils.isEmpty(order.getPage())?"1":order.getPage())-1) * Integer.valueOf(StringUtils.isEmpty(order.getPageSize())?"65536":order.getPageSize());  
			  order.setFromIndex(fromIndex);
			  order.setPageSizes(pagesizes);
		}else{
		PageHelper.startPage(Integer.valueOf(StringUtils.isEmpty(order.getPage())?"1":order.getPage()),Integer.valueOf(StringUtils.isEmpty(order.getPageSize())?"65536":order.getPageSize()),false);
		}
		List<OrderSelectInfoEntity> selectForList = orderSelectInfoEntityMapper.selectForList(order);
		for (OrderSelectInfoEntity orderSelectInfoEntity : selectForList) 
		{
			String orderId = orderSelectInfoEntity.getOrderId();
			String orderType = orderSelectInfoEntity.getOrderType();
			if(orderType.equals(OrderTypeEnum._3.getKey())||orderType==(OrderTypeEnum._3.getKey())){
				orderSelectInfoEntity.setPayStatus(PayStatusEnum._3.getKey());
			}
			OrderInfo orderInfo=new OrderInfo();
			orderInfo.setDeflag("0");
			orderInfo.setRefundOrderId(orderId);
			
		}
		Map<String, Object> selectCountList = orderSelectInfoEntityMapper.selectCountAndAmountList(order);
		Map<String, Object> pageInfomap = new HashMap<>();
		pageInfomap.put("total", (Long)selectCountList.get("count"));
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("pageInfo", pageInfomap);
		map.put("list",selectForList);
		map.put("allTotalAmount", selectCountList.get("all_total_amount"));	
		return map;
	}
	//查询预约单
	@Override
		public Map<String, Object>  appointmentSelectOrderList(SelectOrderVo order) {
			String sort = order.getSort()==null?"":order.getSort();
			if(sort.contains("remainingTime")){
				 sort = sort.replaceAll("remainingTime", "diff_date");
			}
			if(sort.contains("createTime")){
				 sort = sort.replaceAll("createTime", "create_time");
			}
			else{
				sort ="create_time  desc";
				}
			order.setSort(sort);
			if(!StringUtils.isEmpty(order.getStatus())){
				String[] split = order.getStatus().split("\\.");
				order.setOrderStatus(split[0]);
				if(split.length>1){
				order.setPayStatus(split[1]);
				}
			}
			if(!StringUtils.isEmpty(order.getBeginTime())){
				order.setBeginTime(order.getBeginTime()+" 00:00:00");
			}
			if(!StringUtils.isEmpty(order.getEndTime())){
				order.setEndTime(order.getEndTime()+" 23:59:59");
			}
			order.setIspage(false);
			if(StringUtils.isEmpty(order.getMaxReceiptNumber())&&StringUtils.isEmpty(order.getWorkerNames())&&StringUtils.isEmpty(order.getMinReceiptNumber())){
				order.setIspage(true);
				int pagesizes=Integer.valueOf(StringUtils.isEmpty(order.getPageSize())?"65536":order.getPageSize()); 
				int fromIndex = (Integer.valueOf(StringUtils.isEmpty(order.getPage())?"1":order.getPage())-1) * Integer.valueOf(StringUtils.isEmpty(order.getPageSize())?"65536":order.getPageSize());  
				  order.setFromIndex(fromIndex);
				  order.setPageSizes(pagesizes);
			}else{
			PageHelper.startPage(Integer.valueOf(StringUtils.isEmpty(order.getPage())?"1":order.getPage()),Integer.valueOf(StringUtils.isEmpty(order.getPageSize())?"65536":order.getPageSize()));
			}
			List<OrderSelectInfoEntity> selectForList = orderSelectInfoEntityMapper.selectForList(order);
			List<AppointmentOrderSelectInfoEntity> appointmentSelectForList= new ArrayList<AppointmentOrderSelectInfoEntity>();
			for (OrderSelectInfoEntity orderSelectInfoEntity : selectForList) 
			{
				String orderId = orderSelectInfoEntity.getOrderId();
				String orderType = orderSelectInfoEntity.getOrderType();
				if(orderType.equals(OrderTypeEnum._3.getKey())||orderType==(OrderTypeEnum._3.getKey())){
					orderSelectInfoEntity.setPayStatus(PayStatusEnum._3.getKey());
				}
				OrderInfo orderInfo=new OrderInfo();
				orderInfo.setDeflag("0");
				orderInfo.setRefundOrderId(orderId);
				AppointmentOrderSelectInfoEntity appointmentOrderSelectInfoEntity=new AppointmentOrderSelectInfoEntity(); 
				BeanUtils.copyProperties(orderSelectInfoEntity,appointmentOrderSelectInfoEntity);
				appointmentSelectForList.add(appointmentOrderSelectInfoEntity);
				
			}
			PageInfo<OrderSelectInfoEntity> pageInfo = new PageInfo<OrderSelectInfoEntity>(selectForList);
			if(order.isIspage()){
				Map<String, Object> selectCountList = orderSelectInfoEntityMapper.selectCountAndAmountList(order);
				pageInfo.setTotal((Long)selectCountList.get("count"));
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("pagetotal", pageInfo.getTotal());
			map.put("list",appointmentSelectForList);
			return map;
		}
	
	
	@Override
	//查看关联订单
	public List<RelationListDto> relationList(SelectOrderVo order){
//		OrderSelectInfoEntity selectbyOrderId = orderSelectInfoEntityMapper.selectbyOrderId(order.getOrderId());
		OrderInfo selectbyOrderId = orderInfoMapper.getLastOrderInfoById(order.getOrderId());
		String superOrderId = selectbyOrderId.getSuperOrderId();
		if(StringUtils.isEmpty(superOrderId)){
			order.setSuperOrderId(order.getOrderId());
		}else {
			order.setSuperOrderId(superOrderId);
		}
		List<OrderSelectInfoEntity> selectForList = orderSelectInfoEntityMapper.selectRelationList(order);
		List<RelationListDto> relationList=new  ArrayList<RelationListDto>();
		for (OrderSelectInfoEntity orderSelectInfoEntity : selectForList) {
			RelationListDto relationListDto=new RelationListDto();
			String orderType = orderSelectInfoEntity.getOrderType();
			if(orderType.equals(OrderTypeEnum._3.getKey())||orderType==(OrderTypeEnum._3.getKey())){
				relationListDto.setPayStatus(PayStatusEnum._3.getKey());
			}
			 BeanUtils.copyProperties(orderSelectInfoEntity, relationListDto);
			 relationList.add(relationListDto);
		}
		return relationList;
		
	}
	//查询订单详细
	@Override
	public OrderInfoDto  selectOrderInfo(SelectOrderVo order) {
		SOrderInfoEntity selectByPrimaryKey = sOrderInfoEntityMapper.selectByPrimaryKey(order);
		//拼接参数
		OrderInfoDto orderInfoDto=null;
		if(selectByPrimaryKey!=null){
			orderInfoDto=new OrderInfoDto();
			BeanUtils.copyProperties(selectByPrimaryKey, orderInfoDto);
			orderInfoDto.setMoneyStatus(!selectByPrimaryKey.getPayStatus().equals("1"));
			
		}
		Double orderAmount=0.0;
		List<SOrderServiceInfoEntity> orderServiceInfoList = selectByPrimaryKey.getsOrderServiceInfoEntity();
		List<OrderDetailDto> orderDetailList=new ArrayList<OrderDetailDto>();
		if(orderServiceInfoList!=null&&orderServiceInfoList.size()>0){
		for (SOrderServiceInfoEntity sOrderServiceInfoEntity : orderServiceInfoList) {
			OrderServiceInfo orderServiceInfoByServiceId = orderServiceInfoMapper.getOrderServiceInfoByServiceId(sOrderServiceInfoEntity.getRefundServiceId());
			
			OrderDetailDto orderDetail=new OrderDetailDto();
			ChargeInfoDto chargeInfo=new ChargeInfoDto();
			SickRoomInfoDto sickRoomInfo=new SickRoomInfoDto();
			BeanUtils.copyProperties(sOrderServiceInfoEntity, orderDetail);
			if(selectByPrimaryKey.getOrderType().equals("3")&&orderServiceInfoByServiceId!=null){
				orderDetail.setBaseBeginTime(orderServiceInfoByServiceId.getBeginTime());
				orderDetail.setBaseEndTime(orderServiceInfoByServiceId.getEndTime());
				orderDetail.setBaseDay(orderServiceInfoByServiceId.getDay());
			}
			BeanUtils.copyProperties(sOrderServiceInfoEntity, chargeInfo);
			chargeInfo.setDiseaseGrade(sOrderServiceInfoEntity.getIllnessGrade());
			chargeInfo.setDiseaseGradeName(sOrderServiceInfoEntity.getIllnessGradeName());
			BeanUtils.copyProperties(sOrderServiceInfoEntity, sickRoomInfo);
			sickRoomInfo.setBedNumber(sOrderServiceInfoEntity.getHospitalBed());
			orderDetail.setChargeInfo(chargeInfo);
			orderDetail.setSickRoomInfo(sickRoomInfo);
			orderAmount+=sOrderServiceInfoEntity.getActualTotalPrice()==null?0:sOrderServiceInfoEntity.getActualTotalPrice();;
			List<SOrderServiceNurseInfoEntity> orderServiceNurseInfoList = sOrderServiceInfoEntity.getSOrderServiceNurseInfoEntity();
			List<WorkerDto> workerVoList=new ArrayList<WorkerDto>();
			if(orderServiceNurseInfoList!=null&&orderServiceNurseInfoList.size()>0){
				SOrderServiceNurseInfoEntity sOrderServiceNurseInfoEntity = orderServiceNurseInfoList.get(0);
				WorkerInfoDto workerInfo = new WorkerInfoDto();
				BeanUtils.copyProperties(sOrderServiceNurseInfoEntity, workerInfo);
				BeanUtils.copyProperties(sOrderServiceInfoEntity, workerInfo);
				for (SOrderServiceNurseInfoEntity sOrderServiceNurseInfoEntity2 : orderServiceNurseInfoList) {
					WorkerDto workerVo = new WorkerDto(); 
					BeanUtils.copyProperties(sOrderServiceNurseInfoEntity2, workerVo);
					if(!StringUtils.isEmpty(sOrderServiceNurseInfoEntity2.getGroupName())){
						workerVo.setWorkerName(sOrderServiceNurseInfoEntity2.getGroupName());
					}
					workerVo.setHourPay(sOrderServiceNurseInfoEntity2.getOneHourPay());
					workerVoList.add(workerVo);
				}
				workerInfo.setWorkers(workerVoList);
				orderDetail.setWorkerInfo(workerInfo);
				
			}
			else {
				WorkerInfoDto workerInfo = new WorkerInfoDto();
				workerInfo.setWorkers(workerVoList);
				orderDetail.setWorkerInfo(workerInfo);
			}
			
			orderDetailList.add(orderDetail);
			
			}
		orderInfoDto.setOrderDetail(orderDetailList);
		
		
		}else{
			orderInfoDto.setOrderDetail(new ArrayList<>());
		}
		SettlementDto settlementDto=new SettlementDto();
		List<OrderChargeInfo> selectChareList = iChareOrderService.selectChareList(order.getOrderId());
		String serviceOrderTime="";
		if(null!=selectChareList&&selectChareList.size()>0){
			OrderChargeInfo orderChargeInfo = selectChareList.get(0);
			BeanUtils.copyProperties(orderChargeInfo, settlementDto);
			
			String userId = orderChargeInfo.getUserId();
			if(!StringUtils.isEmpty(userId)){
			UserAccount user = userAccountMapper.selectByPrimaryKey(Integer.parseInt(userId));
			if(null!=user){
			String userName = user.getUserRealName();
			settlementDto.setUserName(userName);
			}
			}
			serviceOrderTime=orderChargeInfo.getServiceOrderTime();
			settlementDto.setAmount(orderAmount);
						
		}
		orderInfoDto.setServiceOrderTime(serviceOrderTime);
		orderInfoDto.setReceiptDetail(settlementDto);
		if(orderInfoDto.getOrderUpdateFlag().equals(OrderUpdateFlagEnum._0.getKey())){
			updateOrderUpdateFlag(orderInfoDto.getOrderId());
		}
		return orderInfoDto;
		
	}
	//更改订单已读状态
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	private void updateOrderUpdateFlag (String orderid){
		orderInfoMapper.updateOrderUpdateFlag(OrderUpdateFlagEnum._2.getKey(), orderid);
	}
	//查询未读订单数量
	@Override
	public int selectUnreadOrder (String hospitalId){
		return orderInfoMapper.selectUnreadOrder(hospitalId);
	}
	
	
	
  
}
